package day05;

import java.lang.reflect.Array;
import java.util.Arrays;

public class EasyArrayList implements EasyList {


	private transient Object[] elementData;
//	Object[] elementData;
	private int modCount;
	private int size;
	private static int defaultLength = 10;
	
	

	public EasyArrayList() {
		this(defaultLength);
	}
	
	public EasyArrayList(int length) {
		super();
		if (length<0) {
			throw new IllegalArgumentException("Illegal Capcity: xxx");
		}
		elementData = new Object[length];
	}
	
	public void add(Object o) {
		ensureExplicitCapacity(size+1);
		
//		rangeCheck(size);
		elementData[size++] = o;//先参与计算，再自身+1
//		size++;//同上
	}
	
	
	private void ensureExplicitCapacity(int minCapacity) {
        modCount++;

        // overflow-conscious code
        if (minCapacity - elementData.length > 0)//  length =10  
        {
        	System.out.println("grow");
            grow(minCapacity);
        }
        	
    }
	
	//array.copy
	public void add(int index, Object o) {
		rangeCheckForAdd(index);
		ensureExplicitCapacity(size+1);//
		
		elementData[index] = o;
		size++;
		
		
	}
	
	
	private void rangeCheckForAdd(int index) {
		if (index>size || index <0) 
			throw new IndexOutOfBoundsException("index:"+index+",size:"+ size);
	}
	
	public boolean remove(Object o) {
		for (int i=0; i<elementData.length; i++) {
			Object element = elementData[i];
			if (element.equals(o)) {
				remove(i);
				return true;
			}
		}
		return false;
		
	}
	
	
	
	@Override
	public void remove(int index) {
		
		elementData[index] = null;
		size--;
	}
	@Override
	public void update(int index, Object o) {
		// TODO Auto-generated method stub
		
	}
	@Override
	public Object get(int index) {
		check(index);
		return elementData[index];
	}
	@Override
	public int getSize() {
		// TODO Auto-generated method stub
		return size;
	}
	@Override
	public void rangeCheck(int index) {
		
		if (index >= defaultLength) {
			
		}
	}
	
	/**
	 * 扩容 默认10
	 */
	public void grow(int minCapatity) {
		int oldCapacity = elementData.length;
		int newCapacity = oldCapacity + (oldCapacity>>1);
		if (newCapacity-minCapatity<0)
			newCapacity = minCapatity;
		
		elementData = Arrays.copyOf(elementData, newCapacity);
		
	}
	
	@Override
	public void clear() {
		// TODO Auto-generated method stub
		
	}
	
	private void check(int index) {
		if (index>=defaultLength || index<0) {
			throw new IndexOutOfBoundsException("index--->"+ index);
		}
	}
}
